﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace com.baidu.ai
{
    public class FaceSearch
    {
        // 人脸搜索
        public static string Search(string token, string strbase64)
        {
            //string token = "[调用鉴权接口获取的token]";
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;

            Dictionary<String, String> dic = new Dictionary<string, string>();
            dic.Add("image", strbase64);
            dic.Add("image_type", "BASE64");
            dic.Add("group_id_list", "Users");
            dic.Add("quality_control", "LOW");
            dic.Add("liveness_control", "NONE");
            JavaScriptSerializer js = new JavaScriptSerializer();
            String str = js.Serialize(dic);


            //JObject jObj = JObject.Parse(JsonConvert.SerializeObject(obj));
            //jObj.Add(new JProperty(key, value));
            //return JsonConvert.DeserializeObject(jObj.ToString());

            //Obj prestr = new Obj() { image = "苹果", Price = 5.5, };
            //string str = new JavaScriptSerializer().Serialize(prestr);
            //string inputJsonString = @"[{StudentID:'100',Name:'aaa',Hometown:'china'},{StudentID:'101',Name:'bbb',Hometown:'us'},{StudentID:'102',Name:'ccc',Hometown:'england'}]";
            //JArray jsonObj = JArray.Parse(inputJsonString);
            //String str = "{\"image\":+strbase64+,\"image_type\":\"BASE64\",\"group_id_list\":\"15945927 \",\"quality_control\":\"LOW\",\"liveness_control\":\"NONE\"}";
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            Console.WriteLine("人脸搜索:");
            Console.WriteLine(result);
            return result;
        }
    }
}
